define(function(require, exports, module) {
	var middlware = require('bigfoot/middlware');
	var $ = middlware.get('common'), _dd = require('bigfoot/dhtml/dd');
	
	exports.dialog = {
		init: function(tplEl){
			// debugger
			var frag = document.createElement('div');
			var tpl = typeof tplEl == 'string' ? tplEl : tplEl.value;
			tpl = tpl.replace(/__textarea__/g, 'textarea'); // textarea 不能嵌套 textarea 标签，于是转义
			frag.innerHTML = tpl;
			
			// 不需要加入 空 div；借助该方法获取第一个子元素！
			// this holder do nothing but just wrap mask & dialog
			var dialogHolder = frag.$('div'); 
			// if(!dialogHolder)dialogHolder = frag;// 非div ，就浪费多个 div 吧
			parent.document.body.appendChild(dialogHolder);
			
			var dialog = dialogHolder.$('.box');
			if(window.getComputedStyle(dialog, 'position').position == 'static')
				throw '容器不该是 static 布局。';
			dialog.style.left = (-(~document.body.scrollWidth / 2) - dialog.offsetWidth/2) + 'px';
			dialog.style.top = this.top || '200px';
			
			var closeFn = this.close.bind(this);
			// 删除事件由该类负责
			dialogHolder.$('.closeAction', function(close){
				close.onclick = closeFn;
			});
			dialogHolder.$('.okAction').$(onOk.bind(this));

			this.el = dialogHolder;

			// document.onselectstart = function(e) { return false; }
			// ，代码就把Dialog的left和top设为了鼠标当前位置，可是用户在拖动的时候不会刻意去点Dialog的左上角，这样就跳了，soga！改进一下
			// http://www.cnblogs.com/dolphinX/p/3290520.html
			// http://www.cnblogs.com/dolphinX/p/3293455.html
			dialog.onmousedown = (function(e){
				if(e.target.tagName != 'H1')return;
				e.preventDefault();
				var dd = Object.create(_dd), dialogStyled = dialog.style;
				
				// box 左端 到 鼠标 x 坐标之间的距离，
				// 应由 onmousedown 那一刻，记录 距离，
				// 不要放在 onMoving 里，不然会 一跳 一跳
				// another way
				var boxLeft = dialog.getBoundingClientRect().left,
					diff = e.screenX - boxLeft;
				dd.onMoving = function(e, data){
					dialogStyled.left = (e.screenX - diff) + 'px';
					// dialogStyled.left = (data.x - dialog.clientWidth  /  2) + 'px';
					dialogStyled.top = data.y + 'px';
				}
				dd.el = parent.document; // 可拖放的范围，documement 表示整张桌布
				dd.init();
			});

			parent.document.onkeydown = onEnterAndEsc.bind(this);
		},
		close : function(e, callback){
			e && e.preventDefault();
			parent.document.body.removeChild(this.el);

			parent.document.onkeydown = null;

			this.onClose && this.onClose(e);
			callback && callback();
			return false;
		}
	};

	function onOk(e){
		this.onOk && this.onOk(e);
	}
	var simpleDialogTpl = 
		'<div class="simpleDialog">\
			<div class="box">\
				<button class="closeAction rightTopIcon" title="关闭对话框">×</button>\
				<h1>{0}</h1>\
				<div class="innerPanel">\
					<table align="center"><tr>\
						<td><div  class="{2}Icon"></div></td>\
						<td class="p">{1}</td>\
					</tr></table>\
				</div>\
				<div class="bottomBtns">\
					<button class="closeAction middleBtn stdBtn" title="关闭对话框">关闭</button>\
				</div>\
			</div>\
			<div class="mask"></div>\
		</div>';

	// 代替 alert()
	var simpleDialog = Object.create(exports.dialog);
	// override
	simpleDialog.init = function(title, msg, iconType){
		iconType = iconType || 'alert'; 

		return exports.dialog.init({
			value : simpleDialogTpl.format(title, msg, iconType)
		});
	}
	exports.simpleDialog = simpleDialog;
	exports.ok = function(msg, onDone_callback) {
		var dialog = Object.create(exports.simpleDialog);
		dialog.init("完成", msg, 'ok');

		// 按下【确定】之后的事件处理器
		if(onDone_callback && typeof onDone_callback == 'function'){
			var closeBtns = dialog.el.querySelectorAll('.closeAction');
			for(var i = 0, j = closeBtns.length; i < j; i++)
				closeBtns[i].onClk(onDone_callback);
		}
		return dialog;
	}
	exports.alert = function(msg, onDone_callback) {
		var dialog = Object.create(exports.simpleDialog);
		dialog.init("提示", msg);

		// 按下【确定】之后的事件处理器
		if(onDone_callback && typeof onDone_callback == 'function'){
			var closeBtns = dialog.el.querySelectorAll('.close');
			for(var i = 0, j = closeBtns.length; i < j; i++)closeBtns[i].onClk(onDone_callback);
		}
		return dialog;
	}
	exports.error = function(msg) {
		var dialog = Object.create(exports.simpleDialog);
		dialog.init("错误", msg, 'error');
		return dialog;
	}
	
	// function escClose(){
	// 	if(navigator.userAgent.indexOf('MSIE') !== -1){
	// 		document.attachEvent('onkeydown', function(){
	// 			if(event.keyCode == 27){
	// 				f.call(this, event);
	// 			}
	// 		});
	// 	}else{
	// 		document.addEventListener('keydown', function(e){
	// 			if(e.which == 27){
	// 				f.call(this, e);
	// 			}
	// 		}, false);
	// 	}
	// });

	// 键盘事件
	function onEnterAndEsc(e){
       e = e || event;
        var keycode = e.which || e.keyCode;
        switch(keycode){  
            case 13: //enter   
            	// 如果 form 里有 action，按下回车自动提交
            	var formEl = this.el.$('form');
            	if(formEl && formEl.action){
            		formEl.submit();
            	}
            break;
            case 339: //exit   
            case 340: //back    
            case 27:
            	this.close(); 
        } 
	}
});